package com.tedu._06weibo.exception;

import com.tedu._06weibo.result.JsonResult;
import com.tedu._06weibo.result.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.Locale;

//@ControllerAdvice
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult doHandlerRuntimeException(RuntimeException e){
        log.error(e.getMessage(),e);
        return new JsonResult(Status.OPERATION_ERROR,e.getMessage());
    }
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException e){

        return new JsonResult(Status.OPERATION_ERROR,e.getMessage());
    }
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        String message = e.getFieldError().getDefaultMessage();
        log.warn(message,e);
        return new JsonResult(Status.VALIDAE_FAILED,message);
    }
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException e){
        String message = e.getMessage();
        message = message.substring(message.indexOf(": ") + 1).trim();
        log.warn(message,e);
        return new JsonResult(Status.VALIDAE_FAILED,message);
    }
}
